<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天窗口</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- 整个聊天窗口 -->
<div class="box">
    <!-- title -->
    <div class="title">
        <h3>聊天窗口-李保玲</h3>
    </div>
    <div class="message-list">
    </div>
    <div class="message">
        <textarea id="content" autofocus></textarea>
        <button id="send">发送</button>
    </div>
</div>

<script>

    // 获取元素
    let btn = document.querySelector("#send");
    let content = document.querySelector("#content");
    let messageList = document.querySelector(".message-list");

    let img = "/img/user.jpg";
    let bot = '/img/bot.jpg';

    function formatter(value) {
        let result = "";
        // 判断是否超过20个字符
        while (value.length > 20) {
            // 截取前20个字符
            result += value.substring(0, 20) + "<br/>";
            value = value.substring(20);
        }
        // 判断是否有剩余的字符
        if (value) {
            result += value;
        }

        // textarea 换行会变成 \n
        // 替换换行
        result = result.replaceAll("\n", "<br/>");
        // 替换空格
        result = result.replaceAll(" ", "&nbsp;");
        return result;
    }

    // 绑定点击事件
    btn.onclick = function () {
        // 获取到文本框的内容, trimStart() 去掉前面的空格
        let value = content.value.trimStart();
        content.value = "";
        // 判断是否有内容.字符串判断是否为空,空字符串为 false
        if (value){
            let question = value;
            const result = formatter(value);
            messageList.innerHTML += "<div class='question'><span class='text'>" + result + "</span><img src='" + img + "'/></div>";
            // 回复
            fetch("/startChat", {
                headers: {
                    'Content-Type': 'application/json'
                },
                method: "POST",
                body: question
            }).then((resp) => {
                return resp.json();
            }).then( (json) => {
                console.log(json)
                let content = json.choices[0].message.content;
                let result1 = formatter(content);
                messageList.innerHTML += "<div class='answer'><img src='" + bot + "'/><span class='text'>" + result1 + "</span></div>";
            }).catch((error) => {
                console.log(error);
                messageList.innerHTML += "<div class='answer'><img src='" + bot + "'/><span class='text'>发生意外，请重新提问。</span></div>";
            });
            // 滚动条滚动到最底部
            messageList.scrollTop = messageList.scrollHeight;
        }

        // 输入框获取焦点
        content.focus();
    }

    addEventListener('keydown', function (e) {
        // alt + enter
        if (e.keyCode === 13 && e.altKey) {
            btn.click();
        }
    },false);

    // 为了让用户体验更好,默认让输入框获取焦点
    content.focus();
</script>
</body>
</html>